package org.yzh.scheduler.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yzh.commons.model.APIResult;
import org.yzh.scheduler.model.entity.JobLogDO;
import org.yzh.scheduler.service.ScheduleJobService;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.time.Duration;

@Tag(name = "任务回调API")
@RequestMapping("callback")
@RestController
public class CallbackController {

    @Autowired
    private ScheduleJobService scheduleJobService;

    @Autowired
    private HttpClient httpClient;

    @Operation(summary = "callback")
    @RequestMapping(value = "{key}", method = {RequestMethod.GET, RequestMethod.POST})
    public void callback(@PathVariable String key, HttpServletRequest request) {
        JobLogDO jobLog = JobLogDO.fromKey(key);
        if (jobLog == null)
            return;

        StringBuilder message = new StringBuilder(1024);

        try (BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                message.append(line).append('\n');
            }
        } catch (Exception e) {
        }

        scheduleJobService.callback(jobLog, message.toString());
    }

    /**
     * 客户端例子，对于任务执行较满的接口建议任务结果异步回调通知
     */
    @Operation(summary = "test")
    @RequestMapping(value = "test", method = {RequestMethod.GET, RequestMethod.POST})
    public APIResult test(@RequestParam(required = false) String callbackUrl) {
        new Thread(() -> {
            try {
                //执行任务中...
                Thread.sleep(3000L);

                //通知任务调度系统执行状态
                if (callbackUrl != null) {

                    httpClient.send(HttpRequest.newBuilder()
                            .uri(URI.create(callbackUrl))
                            .timeout(Duration.ofMinutes(2))
                            .POST(BodyPublishers.ofString("SUCCESS"))
                            .build(), HttpResponse.BodyHandlers.ofString());
                }
            } catch (Exception ignored) {
            }
        }).start();

        //立即返回任务触发状态
        return APIResult.SUCCESS;
    }
}